package com.lyxedu.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyxedu.common.Constants;
import com.lyxedu.common.Result;
import com.lyxedu.controller.dto.UserDto;
import com.lyxedu.excption.ServiceException;
import com.lyxedu.mapper.RoleMenuMapper;
import com.lyxedu.pojo.Menu;
import com.lyxedu.pojo.Role;
import com.lyxedu.pojo.RoleMenu;
import com.lyxedu.pojo.User;
import com.lyxedu.services.MenuService;
import com.lyxedu.services.RoleService;
import com.lyxedu.services.UserService;
import com.lyxedu.utils.TokenUtils;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {
    @Resource
    private RoleService roleService;
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Resource
    private MenuService menuService;

    @GetMapping
    public Result list(){
        return Result.success(roleService.list());
    }

    @PostMapping("/delete")
    public Result delete(int id){
        boolean b = roleService.removeById(id);
        return Result.success();
    }

    @PostMapping("/delBatch")
    public Result delete(@RequestBody Integer[] ids){
        List<Integer> list = Arrays.asList(ids);
        boolean b = roleService.removeByIds(list);
        return Result.success();
    }

    @GetMapping("/page")
        public Result page(
                @RequestParam(value = "pageNum",required = false,defaultValue = "1") int pageNum,
                @RequestParam(value = "pageSize",required = false,defaultValue = "5") int pageSize,
                Role role){
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Role::getId);
        queryWrapper.like(role.getUsername()!=null&&role.getUsername()!="",Role::getUsername,role.getUsername());
        queryWrapper.like(role.getAddress()!=null&&role.getAddress()!="",Role::getAddress,role.getAddress());
        queryWrapper.like(role.getEmail()!=null&&role.getEmail()!="",Role::getEmail,role.getEmail());
        Page<Role> pageInfo = new Page<>(pageNum, pageSize);
        roleService.page(pageInfo,queryWrapper);
        return Result.success(pageInfo);
    }


    @PostMapping("/save")
    public Result insert(@RequestBody Role role){
        boolean b = roleService.saveOrUpdateUser(role);
        return Result.success();

    }

    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Role> list = roleService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("avatarUrl", "头像");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }


    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
//        List<User> list = reader.readAll(User.class);

        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<Role> users = CollUtil.newArrayList();
        for (List<Object> row : list) {
            Role user = new Role();
            user.setUsername(row.get(1).toString());
            user.setNickname(row.get(2).toString());
            user.setEmail(row.get(3).toString());
            user.setPhone(row.get(4).toString());
            user.setAddress(row.get(5).toString());
            users.add(user);
        }

        roleService.saveBatch(users);
        return Result.success();
    }

    /**
     * 获取单个用户信息
     * @param username
     * @return
     */
    @GetMapping("/getRole")
    public Result getUserByName(String username){
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(username != null,Role::getUsername,username);
        Role role = roleService.getOne(wrapper);
        return Result.success(role);
    }

    @PostMapping("/rolePermiss")
    public Result roleWithMenu(@RequestBody List<Integer> menuIds){
        Integer roleId = menuIds.remove(menuIds.size() - 1);

        try {
            roleService.saveRoleWithMenu(roleId,menuIds);
            return Result.success();
        }catch (Exception e){
            return Result.error();
        }
    }

    /**
     * 查角色权限
     * @param roleId
     * @return
     */
    @GetMapping("/rolePermisList")
    public Result roleWithMenu(Integer roleId){
        List<RoleMenu> roleMenus = roleMenuMapper.selectByIdList(roleId);
        List<RoleMenu> ids =new ArrayList<>();
        int i =0;
        for (RoleMenu roleMenu : roleMenus) {
            Menu menu = menuService.getById(roleMenu.getMenuId());
            if (menu.getUrl() == null){
                ids.add(roleMenu);
            }
            i++;
        }
        roleMenus.removeAll(ids);
        return Result.success(roleMenus);
    }

}
